#!/bin/bash
# Program:
#       Log the memory information of the specified process periodically. 
# History:
#       2012/09/26  Version: 0.0.7
# Change: 
#       Set the title of terminal with device serial number.

DEVICE=$1
PROCESS=$2
PERIOD=$3
START_TIME=0
END_TIME=0
TOTAL_TIME=0
HOUR=0
MINUTE=0
SECOND=0
LOG_FILE=0

# Ctrl-C trap handler.
trap 'echo;
      TOTAL_TIME=$((${END_TIME}-${START_TIME}));
      echo ${TOTAL_TIME};
      SECOND=$((${TOTAL_TIME}%60));
      MINUTE=$(((${TOTAL_TIME}/60)%60));
      HOUR=$((${TOTAL_TIME}/3600));
      echo "[TotalTime] ${HOUR}:${MINUTE}:${SECOND}" >> ${LOG_FILE};
      exit' 2


# Check and initialize parameters.
if [ -z "${DEVICE}" ]; then
    echo "Usage: $0 DEVICE [PROCESS] [PERIOD]"
    exit 0
fi

if [ -z "${PROCESS}" ]; then
    PROCESS=system
fi 

if [ -z "${PERIOD}" ]; then
    PERIOD=300
fi

LOG_FILE=${PROCESS}_${DEVICE}.meminfo

if [ -f "${LOG_FILE}" ]; then
    read -p "${LOG_FILE} exists; Do you want to override it?: [y/n]" ANSWER
    if [ "${ANSWER}" != "y" -a "${ANSWER}" != "Y" ]; then
        exit
    fi
fi

# Set the title of terminal
echo -ne "\033]0;${1}\007"

# Get and log the device ID (IMEI)
IMEI=`adb -s ${DEVICE} shell dumpsys iphonesubinfo | grep 'Device ID' | awk '{print $4}'`
echo "[IMEI] $IMEI" | tee ${LOG_FILE} 

# Start to log date and memory information
START_TIME=`date +%s`
END_TIME=`date +%s`
date +'[SYSTEM] %m-%d %H:%M:%S' | tee -a ${LOG_FILE}
adb -s ${DEVICE} shell date +'[DEVICE] %m-%d %H:%M:%S' | tee -a ${LOG_FILE}
adb -s ${DEVICE} shell dumpsys meminfo ${PROCESS} | tee -a ${LOG_FILE}
sleep ${PERIOD} 
while true
do
    END_TIME=`date +%s`
    date +'[SYSTEM] %m-%d %H:%M:%S' | tee -a ${LOG_FILE} 
    adb -s ${DEVICE} shell date +'[DEVICE] %m-%d %H:%M:%S' | tee -a ${LOG_FILE}
    adb -s ${DEVICE} shell dumpsys meminfo ${PROCESS} | tee -a ${LOG_FILE}
    sleep ${PERIOD}
done
